//
//  IGShareIgalleryVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/23.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGShareIgalleryVC.h"
#import "ShareDeviceViewController.h"
#import "IGToSharePageApi.h"
#import "IGiGalleryDSlaveEquApi.h"
#import "IGChangeShareTypeApi.h"

@interface IGShareIgalleryVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) IGiGalleryDSlaveEquApi *iGalleryDSlaveEquApi;
@property (nonatomic, strong) IGToSharePageApi *iGSharePageApi;
@property (nonatomic, strong) IGToSharePageModel *model;

@end

@implementation IGShareIgalleryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.title = @"分享设备";
    self.title = NSLocalizedString(@"Sharing Device", nil);
    self.model = [IGToSharePageModel new];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [self requestData];
}

- (void)requestData {
    _iGSharePageApi = [[IGToSharePageApi alloc] initWithMacId:self.equModel.macId];
    
    __weak typeof(self) weakSelf = self;
    [_iGSharePageApi startWithDecodeClass:[IGToSharePageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGToSharePageResp *resp = responseObject;
            weakSelf.model = resp.data;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, -100, 0, 0);
    }
    return _tableView;
}

#pragma mark -<UITableViewDelegate,UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    
    return self.model.slavers.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"IGShareIgalleryVCID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.font = [UIFont font16];
    cell.textLabel.textColor = [UIColor c4Color];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = self.model.nike;
            cell.imageView.image = [UIImage imageNamed:@"iGallery_Bind_Master"];
        } else if (indexPath.row == 1) {
//            cell.textLabel.text = @"分享权限开放";
            cell.textLabel.text = NSLocalizedString(@"Sharing Authorized", nil);
            UISwitch *switchV = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
            switchV.on = [self.model.share integerValue]==1?YES:NO;
            [switchV addTarget:self action:@selector(switChangeValueAction:) forControlEvents:UIControlEventValueChanged];
            cell.accessoryView = switchV;
        }
    } else if(indexPath.section == 1) {
        
        if (indexPath.row == 0) {
//            cell.textLabel.text = @"添加分享用户";
            cell.textLabel.text = NSLocalizedString(@"Add Sharing Users", nil);
            cell.imageView.image = [UIImage imageNamed:@"iGallery_add"];
        } else {
            IGUserInfo *user = self.model.slavers[indexPath.row - 1];
            cell.textLabel.text = user.nike;
            cell.imageView.image = [UIImage imageNamed:@"iGallery_Bind_Slave"];
            
            UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [delBtn setFrame:CGRectMake(0, 0, 50, 30)];
            [delBtn setTitleColor:[UIColor appColor] forState:UIControlStateNormal];
//            [delBtn setTitle:@"删除" forState:UIControlStateNormal];
            [delBtn setTitle:NSLocalizedString(@"Delete", nil) forState:UIControlStateNormal];
            delBtn.titleLabel.font = [UIFont font14];
            cell.accessoryView = delBtn;
            
            __weak typeof(self) weakSelf = self;
            [delBtn setTapActionWithBlock:^{
                [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"Delete Shared Users", nil) message:NSLocalizedString(@"After deleted, this user can't push pictures to this device any more.", nil) cancelButtonTitle:NSLocalizedString(@"Cancel",nil) otherButtonTitles:@[NSLocalizedString(@"Confirm",nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                        // 从数据源中删除
                        [self.model.slavers removeObject:user];
                        // 从列表中删除
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.tableView reloadData];
                        });
                        
                        _iGalleryDSlaveEquApi = [[IGiGalleryDSlaveEquApi alloc] initWithMacId:weakSelf.equModel.macId slaveUid:user.uid type:IGiGalleryDeleteSlaveEquTypeSlave];
                        [_iGalleryDSlaveEquApi startWithDecodeClass:[IGiGalleryDSlaveEquResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
                            if (responseObject) {
                                // 从数据源中删除
                                self.equModel.slaveNum = [NSString stringWithFormat:@"%@",  @([self.equModel.slaveNum integerValue] - 1)];
                            } else {//删除失败恢复
                                // 从数据源中删除
                                [self.model.slavers insertObject:user atIndex:indexPath.row];
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self.tableView reloadData];
                                });
                            }
                        }];
                    }
                }];
            }];
        }
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        ShareDeviceViewController *vc= [[ShareDeviceViewController alloc]init];
        vc.macId = self.equModel.macId;
        [UIViewController ig_pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel * title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 40)];
    title.backgroundColor = [UIColor mainBackgroundColor];
    title.textColor = [UIColor c4Color];
    if (section == 0) {
//        title.text = @"   主绑用户";
        title.text = NSLocalizedString(@"  Primary User", nil);
    } else {
//        title.text = @"   分享用户";
        title.text = NSLocalizedString(@"  Sharing Users", nil);
    }
    
    return title;
}

//分享权限开放
- (void)switChangeValueAction:(UISwitch *)switchV {
    IGChangeShareTypeApi *api = [[IGChangeShareTypeApi alloc] init];
    if (switchV.on) {
        api.shareType = @"2";
    } else {
        api.shareType = @"1";
    }
    api.macId = self.equModel.macId;
    [api startWithDecodeClass:[IGChangeShareTypeResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (!responseObject) {
            switchV.on = !switchV.on;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
